import { login, getProfile, register } from '@/api/system'
import { message } from '@/libs'
import md5 from 'md5'
export default {
  namespaced: true,
  state: () => {
    return {
      // 用户token
      token: '',
      // 用户信息
      userInfo: {}
    }
  },
  mutations: {
    // 修改
    setToken(state, newToken) {
      state.token = newToken
    },
    // 设置用户信息
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    }
  },
  actions: {
    // 登陆
    async login(context, payload) {
      const { password } = payload
      const res = await login({
        ...payload,
        password: password ? md5(password) : ''
      })
      const { token } = res
      context.commit('setToken', token)
      context.dispatch('profile')
    },
    // 获取用户信息
    async profile(context) {
      const data = await getProfile()
      context.commit('setUserInfo', data)
      message(
        'success',
        `欢迎您${
          data.vipLevel
            ? '尊贵的VIP' + data.vipLevel + '用户' + data.nickname
            : data.nickname
        }`,
        6000
      )
    },
    // 退出登录
    logout(context) {
      // 1.清空token
      context.commit('setToken', '')
      // 2.清空用户信息
      context.commit('setUserInfo', '')
      // 3.刷新页面
      location.reload()
    },
    // 注册
    async register(context, payload) {
      const { password } = payload
      try {
        const data = await register({
          ...payload,
          password: md5(password)
        })
      } catch (error) {
        message('error', String(error).replace('Error:', ''), 6000)
      }
    }
  }
}
